/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.business.gasWorkTask.web;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.convert.Convert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.web.business.gasWorkTask.GasWorkTaskRestApi;
import org.opsli.api.wrapper.business.patrolStationRecord.PatrolStationRecordModel;
import org.opsli.api.wrapper.gasWorkTask.GasWorkTaskModel;
import org.opsli.api.wrapper.gasWorkTask.GasWorkTaskRecordModel;
import org.opsli.common.annotation.RequiresPermissionsCus;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.opsli.api.base.result.ResultVo;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.annotation.EnableLog;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.gasWorkTask.entity.GasWorkTask;
import org.opsli.modulars.business.gasWorkTask.entity.GasWorkTaskData;
import org.opsli.modulars.business.gasWorkTask.mapper.GasWorkTaskMapper;
import org.opsli.modulars.business.gasWorkTask.service.IGasWorkTaskService;
import org.opsli.modulars.business.gasWorkTaskRecord.web.GasWorkTaskRecordRestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.*;


/**
 * 燃气派单 Controller
 *
 * @author Ljc
 * @date 2022-07-14 16:35:26
 */
@Api(tags = GasWorkTaskRestApi.TITLE)
@Slf4j
@ApiRestController("/gasWorkTask")
public class GasWorkTaskRestController extends BaseRestController<GasWorkTask, GasWorkTaskModel, IGasWorkTaskService>
    implements GasWorkTaskRestApi {

    @Value("${opsli.fileUrl}")
    private  String fileUrl;

    @Autowired
    private GasWorkTaskRecordRestController gwtrrController;
    @Autowired
    private GasWorkTaskMapper gasWorkTaskMapper;
    /**
    * 工单下发 查一条
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "获得单条工单下发", notes = "获得单条工单下发 - ID")
    @RequiresPermissions("gasworktask_gasworktask_select")
    @Override
    public ResultVo<GasWorkTaskModel> get(GasWorkTaskModel model) {
        // 如果系统内部调用 则直接查数据库
        if(model != null && model.getIzApi() != null && model.getIzApi()){
            model = IService.get(model);
        }
        return ResultVo.success(model);
    }

    /**
    * 工单下发 查询分页
    * @param pageNo 当前页
    * @param pageSize 每页条数
    * @param request request
    * @return ResultVo
    */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @Override
    public ResultVo<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {


        //将request请求中的参数和自定义过滤参数组装到同一个map里
        Map<String, String[]> queryMap = new LinkedHashMap(request.getParameterMap());
        queryMap.put("devid_EQ", new String[]{UserUtil.getSysUser().getCompanyId()});

        QueryBuilder<GasWorkTask> queryBuilder = new WebQueryBuilder<>(entityClazz, queryMap);
        Page<GasWorkTask, GasWorkTaskModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultVo.success(page.getPageData());
    }

    /**
    * 工单下发 新增
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "新增工单下发数据", notes = "新增工单下发数据")
    @RequiresPermissions("gasworktask_gasworktask_insert")
    @EnableLog
    @Override
    public ResultVo<?> insert(GasWorkTaskModel model) {
        String devid=UserUtil.getSysUser().getCompanyId();
        String devname=UserUtil.getSysUser().getCompany();
        String id=UserUtil.getSysUser().getId(); //创建人id
        model.setDevid(devid);
        model.setDevname(devname);
        model.setManager(id);
        // 调用新增方法
        IService.insert(model);
        return ResultVo.success("新增工单下发成功");
    }

    /**
    * 工单下发 修改
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "修改工单下发数据", notes = "修改工单下发数据")
    @RequiresPermissions("gasworktask_gasworktask_update")
    @EnableLog
    @Override
    public ResultVo<?> update(GasWorkTaskModel model) {
        // 调用修改方法
        IService.update(model);
        return ResultVo.success("修改工单下发成功");
    }

    /**
     * 工单 重新派发
     * @param model 模型
     * @return ResultVo
     */
    @ApiOperation(value = "重新派发", notes = "重新派发")
    @RequiresPermissions("gasworktask_gasworktask_toDistributeUpdate")
    @EnableLog
    @Override
    @Transactional(readOnly=false)
    public ResultVo<?> toDistributeUpdate(GasWorkTaskModel model) {

        GasWorkTask task = gasWorkTaskMapper.getById(model.getId());
        if(null != task){
            //先把原数据放到记录表里
            GasWorkTaskRecordModel recordModel=new GasWorkTaskRecordModel();
            recordModel.setDevid(task.getDevid());
            recordModel.setDevname(task.getDevname());
            recordModel.setWorkId(task.getId());
            recordModel.setUserId(task.getUserId());
            recordModel.setUserName(task.getUserName());
            recordModel.setWorkType(task.getWorkType());
            recordModel.setBeginTime(task.getBeginTime());
            recordModel.setEndTime(task.getEndTime());
            recordModel.setFinishTime(task.getFinishTime());
            recordModel.setWorkUserName(task.getWorkUserName());
            recordModel.setWorkUserAddress(task.getWorkUserAddress());
            recordModel.setWorkUserPhone(task.getWorkUserPhone());
            recordModel.setWorkDescription(task.getWorkDescription());
            recordModel.setWorkState(task.getWorkState());
            recordModel.setWorkPic(task.getWorkPic());
            recordModel.setComment(task.getComment());
            recordModel.setReason(task.getReason());
            recordModel.setManager(task.getManager());

            int a=gwtrrController.taskInsert(recordModel);
        }

        model.setWorkState("0");
        // 调用修改方法
        IService.update(model);
        //把原数据清空
        IService.getUpdateId(model.getId());
        return ResultVo.success("重新派发成功");
    }


    /**
    * 工单下发 删除
    * @param id ID
    * @return ResultVo
    */
    @ApiOperation(value = "删除工单下发数据", notes = "删除工单下发数据")
    @RequiresPermissions("gasworktask_gasworktask_update")
    @EnableLog
    @Override
    public ResultVo<?> del(String id){
        IService.delete(id);
        return ResultVo.success("删除工单下发成功");
    }

    /**
    * 工单下发 批量删除
    * @param ids ID 数组
    * @return ResultVo
    */
    @ApiOperation(value = "批量删除工单下发数据", notes = "批量删除工单下发数据")
    @RequiresPermissions("gasworktask_gasworktask_update")
    @EnableLog

    @Override
    public ResultVo<?> delAll(String ids){
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultVo.success("批量删除工单下发成功");
    }


    /**
    * 工单下发 Excel 导出
    * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
    *
    * 导出时，Token认证和方法权限认证 全部都由自定义完成
    * 因为在 导出不成功时，需要推送错误信息，
    * 前端直接走下载流，当失败时无法获得失败信息，即使前后端换一种方式后端推送二进制文件前端再次解析也是最少2倍的耗时
    * ，且如果数据量过大，前端进行渲染时直接会把浏览器卡死
    * 而直接开启socket接口推送显然是太过浪费资源了，所以目前采用Java最原始的手段
    * response 推送 javascript代码 alert 提示报错信息
    *
    * @param request request
    * @param response response
    */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @RequiresPermissionsCus("gasworktask_gasworktask_export")
    @EnableLog
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "exportExcel");
        QueryBuilder<GasWorkTask> queryBuilder = new WebQueryBuilder<>(entityClazz, request.getParameterMap());
        super.excelExport(GasWorkTaskRestApi.SUB_TITLE, queryBuilder.build(), response, method);
    }

    /**
    * 工单下发 Excel 导入
    * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
    * @param request 文件流 request
    * @return ResultVo
    */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @RequiresPermissions("gasworktask_gasworktask_import")
    @EnableLog
    @Override
    public ResultVo<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

    /**
    * 工单下发 Excel 下载导入模版
    * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
    * @param response response
    */
    @ApiOperation(value = "导出Excel模版", notes = "导出Excel模版")
    @RequiresPermissionsCus("gasworktask_gasworktask_import")
    @Override
    public void importTemplate(HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "importTemplate");
        super.importTemplate(GasWorkTaskRestApi.SUB_TITLE, response, method);
    }

    public int gasTaskAdd(GasWorkTaskData gasWorkTaskData){
        GasWorkTaskModel gasModel=new GasWorkTaskModel();
        gasModel.setId(gasWorkTaskData.getId());
        gasModel.setFinishTime(gasWorkTaskData.getFinishTime());
        gasModel.setWorkState(gasWorkTaskData.getWorkState());
        gasModel.setWorkPic(gasWorkTaskData.getWorkPic());
        gasModel.setComment(gasWorkTaskData.getComment());
        gasModel.setReason(gasWorkTaskData.getReason());
        IService.update(gasModel);
        return 1;
    }

    public int gasCommonGet(GasWorkTaskData gasWorkTaskData){
        GasWorkTaskModel gasModel=new GasWorkTaskModel();
        gasModel.setId(gasWorkTaskData.getId());
        gasModel.setWorkState(gasWorkTaskData.getWorkState());
        gasModel.setUserId(gasWorkTaskData.getUserId());
        gasModel.setUserName(gasWorkTaskData.getUserName());
        IService.update(gasModel);
        return 1;
    }

    @Override
    public ResultVo<Map> getFile(String id){
        Map map=new HashMap();
        GasWorkTaskModel model= IService.get(id);
        List<Map> list=new ArrayList<Map>();
        if(ZkUtils.isNotBlank(model.getWorkPic())){
            String[] arr=model.getWorkPic().split(",");
            for(String s:arr){
                Map datamap=new HashMap();
                datamap.put("src",fileUrl+s);
                list.add(datamap);
            }
        }
        map.put("pic",list);
        return ResultVo.success(map);
    }
}
